<template>
  <div class="chat-text">
    <!-- <div v-html="markdownContent" ref="contentRef"></div> -->
    <span
      class="circle"
      v-if="index === 0 && isClosed"
      :style="{
        left: circlePos.left + 8 + 'px',
        top: circlePos.top + 10 + 'px',
      }"
    ></span>
  </div>
</template>
<script setup>
// import { marked } from "marked";
const props = defineProps({
  content: {
    type: String,
    default: "",
  },
  index: {
    type: Number,
    default: 0,
  },
  isClosed: {
    type: Boolean,
    default: false,
  },
});
const circlePos = reactive({
  left: 0,
  top: 0,
});
// const markdownContent = computed(() => {
//   return marked(props.content);
// });

const contentRef = ref(null);

const getLastTextNode = (dom) => {
  const children = dom.childNodes;
  for (let i = children.length - 1; i >= 0; i--) {
    const child = children[i];
    if (child.nodeType === Node.TEXT_NODE && /\S/.test(child.nodeValue)) {
      child.nodeValue = child.nodeValue.replace(/\s+$/, " ");
      return child;
    } else if (child.nodeType === Node.ELEMENT_NODE) {
      const last = getLastTextNode(child);
      if (last) {
        return last;
      }
    }
  }
  return null;
};

const updateCirclePos = () => {
  const contentDom = contentRef.value;
  const lastText = getLastTextNode(contentDom);
  const textNode = document.createTextNode("点");

  if (lastText) {
    lastText.parentElement.appendChild(textNode);
  } else {
    contentDom.appendChild(textNode);
  }
  const domRect = contentDom.getBoundingClientRect();
  const range = document.createRange();
  range.setStart(textNode, 0);
  range.setEnd(textNode, 0);
  const rect = range.getBoundingClientRect();
  circlePos.left = rect.left - domRect.left;
  circlePos.top = rect.top - domRect.top;
  textNode.remove();
};
onMounted(() => {
  updateCirclePos();
});
onUpdated(() => {
  updateCirclePos();
});
</script>
<style lang="scss" scope>
div.chat-text {
  width: fit-content;
  padding: 5px 10px 5px 20px;
  border-radius: 0 9px 9px 9px;
  background: #f3f3f3;
  color: #2c2c2c;
  font-size: 14px;
  font-weight: 400;
  margin-top: 4px;
  position: relative;
}
span.circle {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #000;
  margin-left: 2px;
  animation: blink 0.7s infinite;
  position: absolute;
  left: 0;
  top: 0;
}
@keyframes blink {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
</style>
